#include "serverform.h"
#include "ui_serverform.h"
#include <QDebug>
#include <QSqlDatabase>

ServerForm::ServerForm(QWidget *parent, QSqlDatabase *db) :
    QWidget(parent),
    ui(new Ui::ServerForm)
{
    ui->setupUi(this);
    this->db = *db;
}

ServerForm::~ServerForm()
{
    delete ui;
}

void ServerForm::on_startPushButton_clicked()
{
    tcpServer.listen(QHostAddress::Any, 10002);
    connect(&tcpServer, SIGNAL(newConnection()), this, SLOT(newConnect()));
}

void ServerForm::newConnect()
{
    tcpSocket = tcpServer.nextPendingConnection(); //得到每个连进来的socket
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readMessage())); //有可读的信息，触发读函数槽
}
/****************************************************************************
 *
 * 接收数据格式为：  影厅名|Ip|端口
 * param
 * param
 * param
 * return
 *****************************************************************************/
void ServerForm::readMessage()
{
    QByteArray qba= tcpSocket->readAll(); //读取
    QString ip=QVariant(qba).toString();
    doWork(ip);
}

void ServerForm::doWork(QString ip)
{
    Device dev;
    model = new QSqlQueryModel(this);


    QString sql = tr("select"
                     " cinema_hall, dev_ip, fix_ftl, fix_lc, fix_rc, fix_cc, fix_hb,"
                     " fix_la, fix_ra, start_datetime, end_datetime"
                     " from tb_dev_corrected_value_conf where dev_ip = '%1' ").arg(ip);
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        QMessageBox::information(this, tr("错误"), tr("执行SQL失败"));
        qDebug()<<"sql==="<<sql<<endl;
    }

    if(model->rowCount() < 0)
    {
        QMessageBox::information(NULL, tr("错误"), tr("播放服务器发送的IP地址无效，请检查播放服务器的配置。"));
        return ;
    }
    for(int i = 0; i<model->rowCount(); i++)
    {
        dev.theaterNo = model->data(model->index(i, 0)).toString();
        dev.ip = model->data(model->index(i, 1)).toString();
        dev.port = 10001;
        dev.fix_ftl = model->data(model->index(i, 2)).toDouble();
        dev.fix_lc = model->data(model->index(i, 3)).toDouble();
        dev.fix_rc = model->data(model->index(i, 4)).toDouble();
        dev.fix_cc = model->data(model->index(i, 5)).toDouble();
        dev.fix_hb = model->data(model->index(i, 6)).toDouble();
        dev.fix_la = model->data(model->index(i, 7)).toDouble();
        dev.fix_ra = model->data(model->index(i, 8)).toDouble();
        dev.stime = model->data(model->index(i, 9)).toTime();
        dev.etime = model->data(model->index(i, 10)).toTime();

    }
    delete model;
    model = NULL;
    thread.setDevice(dev);
    thread.setTestModel(SERVER_MODEL);
    thread.start();
}

void ServerForm::on_closePushButton_clicked()
{
    close();
}

void ServerForm::on_stopPushButton_clicked()
{
    ui->startPushButton->setEnabled(false);
    tcpServer.close();
    thread.Stop(true);

}
